package com.example.demomethodpermissions.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)  // 方法级别的权限配置许可
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()

                .formLogin();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(){

        PasswordEncoder delegatingPasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        UserDetails user1 = User.builder()
                .username("yang")
                .password(delegatingPasswordEncoder.encode("123123"))

                // 用户权限
                .roles("user")
                .authorities("query", "export")
                .build();
        UserDetails user2 = User.builder()
                .username("wang")
                .password(delegatingPasswordEncoder.encode("123123"))

                // 用户权限
                .roles("admin")
                .authorities("query", "delete","update","insert")
                .build();
        return new InMemoryUserDetailsManager(user1, user2);
    }

}

